from flask import Blueprint, request, jsonify, Response, stream_with_context
from flask_jwt_extended import jwt_required, get_jwt_identity
from ..services.ai_service import ai_service
import json

# 创建蓝图
ai_bp = Blueprint('ai', __name__)

@ai_bp.route('/chat', methods=['POST'])
@jwt_required(optional=True)
def chat():
    """
    AI助手聊天接口
    
    请求体:
    {
        "message": "用户输入的消息",
        "history": [可选] 对话历史记录
    }
    
    响应:
    {
        "success": true/false,
        "message": "AI回复的消息",
        "error": "错误信息（如果有）"
    }
    """
    try:
        # 获取请求数据
        data = request.get_json()
        
        if not data or 'message' not in data:
            return jsonify({
                'success': False,
                'error': '请求参数错误，缺少message字段'
            }), 400
        
        # 获取用户ID（如果已登录）
        user_id = get_jwt_identity()
        
        # 获取用户消息和历史记录
        user_message = data.get('message', '')
        history = data.get('history', [])
        
        # 检查是否需要流式响应
        stream = data.get('stream', False)
        
        if stream:
            # 流式响应
            def generate():
                try:
                    for chunk in ai_service.generate_stream_response(user_message, history):
                        # 将每个文本块包装成JSON格式
                        yield f"data: {json.dumps({'content': chunk})}\n\n"
                    # 发送结束标记
                    yield "data: [DONE]\n\n"
                except Exception as e:
                    yield f"data: {json.dumps({'error': str(e)})}\n\n"
            
            # 设置响应头以支持流式传输
            response = Response(stream_with_context(generate()), content_type='text/event-stream')
            response.headers['Cache-Control'] = 'no-cache'
            response.headers['Connection'] = 'keep-alive'
            response.headers['Access-Control-Allow-Origin'] = '*'
            return response
        else:
            # 调用AI服务生成回复
            result = ai_service.generate_response(user_message, history)
            
            if result['success']:
                return jsonify({
                    'success': True,
                    'message': result['message']
                })
            else:
                return jsonify({
                    'success': False,
                    'error': result.get('error', 'AI服务响应失败')
                }), 500
                
    except Exception as e:
        return jsonify({
            'success': False,
            'error': f'服务器内部错误: {str(e)}'
        }), 500

@ai_bp.route('/health', methods=['GET'])
def health_check():
    """
    AI服务健康检查接口
    """
    try:
        # 简单的健康检查，确认API密钥是否配置
        if ai_service.api_key:
            return jsonify({
                'success': True,
                'status': 'AI服务正常'
            })
        else:
            return jsonify({
                'success': False,
                'error': 'AI服务配置缺失'
            }), 500
    except Exception as e:
        return jsonify({
            'success': False,
            'error': f'AI服务异常: {str(e)}'
        }), 500